use aes::Aes128;
use block_modes::{BlockMode, Cbc};
use block_modes::block_padding::{Pkcs7, NoPadding};

type Aes128Cbc = Cbc<Aes128, NoPadding>;

pub fn encrypt() {
    // let key = hex!("000102030405060708090a0b0c0d0e0f");
    // let mut key = [0u8; 64];
    let key = "zxcvbnmasd123456".as_bytes();
    // let mut iv = [0u8; 64];
    let iv = "qwertyuiopasdfgh".as_bytes();

    // let iv = hex!("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
    // let plaintext = "Hello world!".into();
    let plaintext = padding_string("Hello world!".into());  // NoPadding, 需要手动补全字符

    let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();

    // buffer must have enough space for message+padding
    let n = plaintext.len() % 16 + 1;
    let mut buffer = vec![0u8; 16 * n];
    // let mut buffer = [0u8; 16*2];
    // copy message to the buffer
    let pos = plaintext.len();
    buffer[..pos].copy_from_slice(plaintext.as_bytes());
    let ciphertext = cipher.encrypt(&mut buffer, pos).unwrap();
    let res = hex::encode(ciphertext);
    println!("{}", res.to_string());

    let t = "389C8E49D70FF4AA47C151BED49D1D16";
    let cipher: Cbc<Aes128, NoPadding> = BlockMode::new_from_slices(&key, &iv).unwrap();
    let mut buf = hex::decode(t).unwrap();
    let decodetext = cipher.decrypt_vec(&mut buf).unwrap();
    let res = std::str::from_utf8(&decodetext).unwrap();
    println!("{}", res.to_string());
}

fn padding_string(text: String) -> String {
    let size = 16;
    let n = size - (text.as_bytes().len() % size);

    format!("{}{}", text, String::from_utf8(vec![b' '; n]).unwrap())
}